package projorientado.spi;

import java.util.Enumeration;
import java.util.Hashtable;

public abstract class GenericServiceProviderInterface<T> {
    
    private Hashtable<String,ServiceProvider<T>> providers = new Hashtable();
    
    public T getService(String s) {
        int i = s.indexOf("://");
        if(i == -1)
            return null;
        String name = s.substring(0, i);
        String param = s.substring(i+3);
        return getService(name,param);
    }
    
    public T getService(String serviceName, String param) {
        ServiceProvider<T> sp = getServiceProvider(serviceName);
        if(sp == null)
            return null;
        return sp.getService(param);
    }
    
    public Enumeration<String> enumerateServicesProviders() {
        return providers.keys();
    }
    
    public void registerServiceProvider(String serviceName, ServiceProvider<T> sp) {
        providers.put(serviceName.toLowerCase(), sp);
    }
    
    public void unregisterServiceProvider(String serviceName) {
        providers.remove(serviceName.toLowerCase());
    }
    
    public ServiceProvider<T> getServiceProvider(String serviceName) {
        return providers.get(serviceName.toLowerCase());
    }
    
    public static boolean searchServiceProvider(String className) {
        try {
           Class.forName(className); 
           return true;
        } catch(Exception e) {
            return false;
        }
    }
}
